console.log('this is databook')

let getSelection = function () {
    var txt = window.getSelection ? window.getSelection().toString() : document.selection.createRange().text
    return txt
}

let showCollectionData = function (selectTxt) {
    let proxyHref = window.location.href // 获取整个url： http://localhost:8082/Index.html?name=tom
    let href = decodeURI(atob(getQueryVariable('url')))
    let host = window.location.host // 获取域名加端口号： localhost:8082
    let protocol = window.location.protocol // 获取协议： http:
    let domain = document.domain // 获取域名： localhost
    let referrer = document.referrer
    let rootUri = protocol + '//' + host
    // let title = document.getElementsByTagName('head')[0].getElementsByTagName('title')[0].innerText
    let title = document.title

    top.postMessage({
        action: 'COLLECTION_DATA',
        data: {
            href,
            host,
            referrer,
            rootUri,
            title,
            selectTxt
        }
    }, '*')
}

let showCollectionVideo = function (urls) {
    top.postMessage({
        action: 'COLLECTION_VIDEO',
        data: urls
    }, '*')
}

let showCollectionAudio = function (urls) {
    top.postMessage({
        action: 'COLLECTION_AUDIO',
        data: urls
    }, '*')
}

let html2markdown = function (html) {
    let referrer = document.referrer

    top.postMessage({
        action: 'HTML_TO_MARKDOWN',
        data: html
    }, '*')
}

/*
 * html元素的外联、内联css样式转换为内嵌css样式
 */
let emptyNodeMap = {}
let elementOuterStyle2InnerStyle = function (element) {
    let nodeName = element.nodeName
    let emptyNode = emptyNodeMap[nodeName]
    if (!emptyNode) {
        emptyNode = document.createElement(nodeName)
        document.body.appendChild(emptyNode)
        emptyNodeMap[nodeName] = emptyNode
    }

    let elementStyles = getComputedStyle(element, null)
    let nodeStyles = getComputedStyle(emptyNode, null)

    for (let index in elementStyles) {
        if(index && !isNaN(parseInt(index))){
            let key = elementStyles[index]
            
            let value = elementStyles[key]
            let nodeValue = nodeStyles[key]
            if (value && value != nodeValue) {
                element.style[key] = value
            }
        }
    }

    for (let index = 0; index < element.children.length; index++) {
        let childrenElement = element.children[index]
        elementOuterStyle2InnerStyle(childrenElement)
    }
}

let fnMap = {
    mouseoverElement (e) {
        e.target.style.borderBack = e.target.style.border
        e.target.style.borderChange = true
        e.target.style.border = "1px solid red"
    },
    mouseoutElement (e) {
        if (e.target.style.borderChange == true) {
            e.target.style.border = e.target.style.borderBack
            e.target.style.borderChange = false
        }
    },
    pickupElement (e) {
        fnMap.closePickupElement(e)
        /*
        let innerText = e.target.innerText
        let innerHTML = e.target.innerHTML
        let outerText = e.target.outerText
        let outerHTML = e.target.outerHTML
        console.log(innerText)
        console.log(innerHTML)
        console.log(outerText)
        console.log(outerHTML)
        */
        elementOuterStyle2InnerStyle(e.target)
        let outerHTML = e.target.outerHTML
        html2markdown(outerHTML)
    },
    openPickupElement (e) {
        // 检索元素，鼠标移到元素上添加红色边框
        document.addEventListener("mouseover", fnMap.mouseoverElement)
        // 检索元素，鼠标移出元素时边框还原
        document.addEventListener("mouseout", fnMap.mouseoutElement)
        // 点击获取当前元素
        document.addEventListener("click", fnMap.pickupElement, true)
    },
    closePickupElement (e) {
        fnMap.mouseoutElement(e)
        // 检索元素，鼠标移到元素上添加红色边框
        document.removeEventListener("mouseover", fnMap.mouseoverElement)
        // 检索元素，鼠标移出元素时边框还原
        document.removeEventListener("mouseout", fnMap.mouseoutElement)
        // 点击获取当前元素
        document.removeEventListener("click", fnMap.pickupElement, true)
    },
    pickupVideo (e) {
        let elements = document.getElementsByTagName('video')
        let urls = []
        for (let i = 0; i < elements.length; i++) {
            let element = elements[i]
            let src = element.getAttribute('src')
            urls.push(src)
        }
        showCollectionVideo(urls)
    },
    pickupAudio (e) {
        let elements = document.getElementsByTagName('audio')
        let urls = []
        for (let i = 0; i < elements.length; i++) {
            let element = elements[i]
            let src = element.getAttribute('src')
            urls.push(src)
        }
        showCollectionAudio(urls)
    }
}

/*
自定义右击菜单、关闭右击菜单
*/
let bindOncontextmenu = function () {
    /**
     * 
    <div class="contextmenu" id="context">
        <ul>
            <li><a href="javascript:;">复制</a></li>
            <li><a href="javascript:;">粘贴</a> </li>
            <li><a href="javascript:;">剪切</a></li>
            <li><a href="javascript:;">下载</a></li>
            <li><a href="javascript:;">上传</a></li>
        </ul>
    </div>
    */

    let contextmenuUi = [
        {
            innerText: '复制',
            href: 'javascript:;',
            onclick: function () {
                try{
                    if(document.execCommand('copy', false, null)){
                        console.log('复制success')
                    } else{
                        console.log('复制failed')
                    }
                } catch(err){
                    console.log(err)
                }
            }
        },
        {
            innerText: '采集',
            href: 'javascript:;',
            onclick: function (){
                let selectTxt = getSelection()
                console.log(selectTxt)
                showCollectionData(selectTxt)
            }
        },
        {
            innerText: '采集视频',
            href: 'javascript:;',
            onclick: fnMap.pickupVideo
        },
        {
            innerText: '采集音频',
            href: 'javascript:;',
            onclick: fnMap.pickupAudio
        },
        {
            innerText: '检索元素',
            href: 'javascript:;',
            onclick: fnMap.openPickupElement
        },
        {
            innerText: '关闭检索',
            href: 'javascript:;',
            hide: true,
            onclick: fnMap.closePickupElement
        }
    ]

    //获取body
    var body = document.getElementsByTagName("body")[0]

    //添加div
    var div = document.createElement("div")
    div.setAttribute('id', 'context')
    div.setAttribute('class', 'contextmenu')

    var ul = document.createElement("ul")

    contextmenuUi.forEach(item => {
        if (!item.hide) {
            var li = document.createElement("li")
            var a = document.createElement("a")
            a.setAttribute('href', item.href || 'javascript:;')
            a.innerText = item.innerText
            a.addEventListener('click', item.onclick)
            li.appendChild(a)
            ul.appendChild(li)
        }
    })

    div.appendChild(ul)
    body.appendChild(div)

    // 监听右击菜单
    document.oncontextmenu = function(env){
        //env 表示event事件
        // 兼容event事件写法
        var e = env || window.event

        e.preventDefault()
        fnMap.closePickupElement(e)

        // 获取菜单，让菜单显示出来
        var context = document.getElementById("context")
        context.style.display = "block"

        //  让菜单随着鼠标的移动而移动
        //  获取鼠标的坐标
        // var x = e.clientX
        // var y = e.clientY
        var x = e.pageX
        var y = e.pageY

        //  获取窗口的宽度和高度
        // var w = window.innerWidth
        // var h = window.innerHeight
        var w = document.body.offsetWidth
        var h = document.body.offsetHeight

        //  调整宽度和高度
        context.style.left = Math.min(w - context.offsetWidth, x) + "px"
        context.style.top = Math.min(h - context.offsetHeight, y) + "px"

        // return false可以关闭系统默认菜单
        return false
    }

    // 当鼠标点击后关闭右键菜单
    document.addEventListener('click', function() {
        var contextmenu = document.getElementById("context")
        contextmenu.style.display = "none"
    })
}

let init = function () {
    bindOncontextmenu()
}

document.addEventListener("DOMContentLoaded", function(event) {
    init()
})
